package com.store.controller;

import com.store.service.ex.*;
import com.store.util.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpSession;

@Api("控制器基类")
@ControllerAdvice
public class BaseController {

    /**
     * 异常状态码
     *      插入、删除、修改、更新 ：600起
     *      其余 ：500起
     */

    @ApiOperation("统一异常处理")
    @ResponseBody
    @ExceptionHandler(ServiceException.class)
    public JsonResult HandleException(Throwable e, HttpSession session){
        JsonResult jsonResult = new JsonResult();
        System.out.println(e.getMessage());
        if(e instanceof UserNotFoundException){
            jsonResult.setState(501);
            jsonResult.setMessage("用户不存在");
        }else if(e instanceof UserExistsException){
            jsonResult.setState(502);
            jsonResult.setMessage("用户已经存在");
        }else if(e instanceof PasswordErrorException){
            jsonResult.setState(503);
            jsonResult.setMessage("用户密码错误");
        }else if(e instanceof ProductNotFoundException){
            jsonResult.setState(504);
            jsonResult.setMessage("商品不存在");
        }else if(e instanceof CartNotFoundException){
            jsonResult.setState(505);
            jsonResult.setMessage("购物车数据不存在");
        }else if(e instanceof OrderNotFoundException){
            jsonResult.setState(506);
            jsonResult.setMessage("订单数据不存在");
        }else if(e instanceof AddressNotFoundException){
            jsonResult.setState(507);
            jsonResult.setMessage("收获地址数据不存在");
        }else if(e instanceof InsertException){
            jsonResult.setState(601);
            jsonResult.setMessage("插入数据时产生未知的错误");
        }else if(e instanceof UpdateException){
            jsonResult.setState(602);
            jsonResult.setMessage("更新数据时产生未知的错误");
        }else if(e instanceof DeleteException){
            jsonResult.setState(603);
            jsonResult.setMessage("删除数据时产生未知的错误");
        }
        return jsonResult;
    }
}
